package com.hckj.jianzhijia;

import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import com.rey.material.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.SaveCallback;
import com.hckj.jianzhijia.controllers.PublishController;
import com.hckj.jianzhijia.listeners.OnBackClickListener;
import com.hckj.jianzhijia.model.City;
import com.hckj.jianzhijia.model.Job;
import com.hckj.jianzhijia.model.Province;
import com.hckj.jianzhijia.model.Region;
import com.hckj.jianzhijia.networks.GetCityNetWork;
import com.hckj.jianzhijia.networks.GetProvinceNetWork;
import com.hckj.jianzhijia.networks.GetRegionNetWork;
import com.hckj.jianzhijia.popupwindows.PublishPopWinJobType;
import com.hckj.jianzhijia.popupwindows.PublishPopupWindowCity;
import com.hckj.jianzhijia.popupwindows.PublishPopupWindowGender;
import com.hckj.jianzhijia.popupwindows.PublishPopupWindowPayType;
import com.hckj.jianzhijia.popupwindows.PublishPopupWindowProvince;
import com.hckj.jianzhijia.popupwindows.PublishPopupWindowRegion;
import com.hckj.jianzhijia.utils.Data;
import com.hckj.jianzhijia.utils.ExceptionUtils;
import com.hckj.jianzhijia.utils.StateConstant;
import com.hckj.jianzhijia.utils.ToastUtils;
import com.rey.material.app.Dialog;
import com.rey.material.app.DialogFragment;
import com.rey.material.app.SimpleDialog;

import java.util.ArrayList;

import butterknife.ButterKnife;
import butterknife.InjectView;

public class PublishActivity extends BaseActivity implements
            PublishPopWinJobType.PublishPopWinJobTypeInterface,
                        PublishPopupWindowGender.PublishPopWinGenderInterface,
                        PublishPopupWindowPayType.PublishPopWinPayTypeInterface,
                        PublishPopupWindowProvince.PublishPopWinProvinceInterface,
                        PublishPopupWindowCity.PublishPopWinCityInterface,
                        PublishPopupWindowRegion.PublishPopWinRegionInterface,
                        GetCityNetWork.NetWorkInterface,
                        GetProvinceNetWork.NetWorkInterface,
                        GetRegionNetWork.NetWorkInterface {

    private static final int SELECT_CONTACTOR_CODE = 1234;
    @InjectView(R.id.imgv_go_back)
    ImageView imgvGoBack;
    @InjectView(R.id.rl_toolbar)
    RelativeLayout rlToolbar;
    @InjectView(R.id.edt_job_name)
    EditText edtJobName;
    @InjectView(R.id.rl_choose_job_type)
    RelativeLayout rlChooseJobType;
    @InjectView(R.id.rl_pay_type)
    RelativeLayout rlPayType;
    @InjectView(R.id.rl_choose_gender)
    RelativeLayout rlChooseGender;
    @InjectView(R.id.edt_job_date)
    EditText edtJobDate;
    @InjectView(R.id.edt_job_time)
    EditText edtJobTime;
    @InjectView(R.id.edt_job_salary)
    EditText edtJobSalary;
    @InjectView(R.id.edt_job_describe)
    EditText edtJobDescribe;
    @InjectView(R.id.edt_contact_phone)
    EditText edtContactPhone;
    @InjectView(R.id.edt_contact_email)
    EditText edtContactEmail;
    @InjectView(R.id.edt_job_address)
    EditText edtJobAddress;
    @InjectView(R.id.edt_people_num)
    EditText edtPeopleNum;
    @InjectView(R.id.ll_parent)
    LinearLayout llParent;
    @InjectView(R.id.cb_read_protocol)
    CheckBox cbReadProtocol;
    @InjectView(R.id.tv_read_protocol)
    TextView tvReadProtocol;
    @InjectView(R.id.btn_publish)
    Button btnPublish;
    @InjectView(R.id.edt_contact_people)
    EditText edtContactPeople;
    @InjectView(R.id.tv_job_type)
    TextView tvJobType;
    @InjectView(R.id.tv_pay_type)
    TextView tvPayType;
    @InjectView(R.id.tv_gender_type)
    TextView tvGenderType;
    @InjectView(R.id.tv_choose_province)
    TextView tvChooseProvince;
    @InjectView(R.id.tv_choose_city)
    TextView tvChooseCity;
    @InjectView(R.id.tv_choose_region)
    TextView tvChooseRegion;
    @InjectView(R.id.tv_title)
    TextView tvTitle;
    @InjectView(R.id.imgv_people_list)
    ImageView imgvPeopleList;
    private String jobName;
    private Integer jobType;//不存在默认值
    private String workDate;//对工作日期的描述
    private String workTime;//对工作时间的描述
    private String requestNum;//不存在默认值
    private Integer payType = 1;//存在默认值
    private String salary;//不存在默认值
    private String describe;
    private Integer genderRequest = 0;
    //private Integer heightRequest = 0;//目前暂时没有确定怎么处理这个短的数据
    private String contactEmail;
    private String contactPhone;
    private String contactName;
    private String workAddress;
    private Integer cityId = -1;
    private Integer provinceId = -1;
    private Integer regionId = -1;
    private boolean hasReadProtocol = false;


    private PublishPopWinJobType publishPopWinJobType;
    private PublishPopupWindowGender publishPopupWindowGender;
    private PublishPopupWindowPayType publishPopupWindowPayType;

    private PublishPopupWindowCity publishPopupWindowCity;
    private PublishPopupWindowProvince publishPopupWindowProvince;
    private PublishPopupWindowRegion publishPopupWindowRegion;

    private GetProvinceNetWork getProvinceNetWork;
    private GetCityNetWork getCityNetWork;
    private GetRegionNetWork getRegionNetWork;


    private PublishController publishController;
    private ProgressDialog loadingDialog;


    private boolean ifModify = false;
    private Job job = null;
    private boolean netWorIsOn = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish);
        ButterKnife.inject(this);
        ifModify = getIntent().getBooleanExtra("ifModify", false);
        if (ifModify) {
            job = new Job((AVObject) getIntent().getParcelableExtra("job"));
            tvTitle.setText("修改");
            initModifyData();
        } else {
            job = new Job();
        }

        publishController = new PublishController(this);
        loadingDialog = new ProgressDialog(this);
        loadingDialog.setCancelable(false);
        loadingDialog.setMessage("正在上传");

        initData();
        initPopupWin();
        initEvent();


    }

    private void initData() {
        edtContactPeople.setText(AVUser.getCurrentUser().getString("name"));
        edtContactEmail.setText(AVUser.getCurrentUser().getEmail());
        edtContactPhone.setText(AVUser.getCurrentUser().getUsername());
    }


    private void initPopupWin() {
        publishPopWinJobType = new PublishPopWinJobType(this, this, llParent, rlChooseJobType);
        publishPopupWindowGender = new PublishPopupWindowGender(this, this, llParent, rlChooseGender);
        publishPopupWindowPayType = new PublishPopupWindowPayType(this, this, llParent, rlPayType);

    }

    private void initEvent() {


        imgvPeopleList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
                startActivityForResult(i, SELECT_CONTACTOR_CODE);
            }
        });
        tvChooseProvince.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (netWorIsOn) {
                    return;
                }
                cityId = -1;
                regionId = -1;
                tvChooseCity.setText("地区");
                tvChooseRegion.setText("城市");
                netWorIsOn = true;
                getProvinceNetWork = new GetProvinceNetWork(PublishActivity.this);
                getProvinceNetWork.execute();
            }
        });

        tvChooseCity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (netWorIsOn) {
                    return;
                }
                regionId = -1;
                tvChooseRegion.setText("城市");
                if (provinceId == -1) {
                    ToastUtils.showToast(getApplicationContext(), "请选择地区");
                    return;
                } else {
                    netWorIsOn = true;
                    getCityNetWork = new GetCityNetWork(provinceId, PublishActivity.this);
                    getCityNetWork.execute();
                }
            }
        });

        tvChooseRegion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (netWorIsOn) {
                    return;
                }

                if (provinceId == -1) {
                    ToastUtils.showToast(getApplicationContext(), "请选择国别");
                    return;
                } else if (cityId == -1) {
                    ToastUtils.showToast(getApplicationContext(), "请选择地区");
                    return;
                } else {
                    netWorIsOn = true;
                    getRegionNetWork = new GetRegionNetWork(cityId, PublishActivity.this);
                    getRegionNetWork.execute();
                }
            }
        });


        imgvGoBack.setOnClickListener(new OnBackClickListener(this));
        tvReadProtocol.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(), WebPageActivity.class);
                intent.putExtra("WebPageType", WebPageActivity.WEBPAGE_PUBLISH_PROTOCAL);
                startActivity(intent);
            }
        });
        btnPublish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getDataFromEdt();
                if (!publishController.checkAllData(contactName,
                                                               contactEmail,
                                                               contactPhone,
                                                               describe,
                                                               genderRequest,
                                                               jobName,
                                                               jobType,
                                                               requestNum,
                                                               salary,
                                                               workDate,
                                                               workTime,
                                                               workAddress,
                                                               hasReadProtocol,
                                                               cityId,
                                                               provinceId,
                                                               regionId)) {
                    return;
                } else {
                    loadingDialog.show();
                    if (ifModify) {
                        job.setJobObject(AVObject.createWithoutData(Job.JOB_TABLE, (job.getJobObject()).getObjectId()));
                    }
                    job.setContactName(contactName);
                    job.setContactEmail(contactEmail);
                    job.setContactPhone(contactPhone);
                    job.setDescribe(describe);
                    job.setGenderRequest(genderRequest);
                    job.setJobName(jobName);
                    job.setJobType(jobType);
                    job.setRequestNum(requestNum);
                    job.setSalary(salary);
                    job.setWorkAddress(workAddress);
                    job.setWorkDate(workDate);
                    job.setWorkTime(workTime);
                    job.setPayType(payType);
                    job.setProvinceId(provinceId);
                    job.setCityId(cityId);
                    job.setRegionId(regionId);

                    if (jianzhijiaApplacation.getCompanyUser().isIdentified()) {
                        job.setJobState(StateConstant.JOB_STATE_PUBLISHED);//无需审核，正在进行中
                    } else {
                        job.setJobState(StateConstant.JOB_STATE_PUBLISHING);//需要审核，正在进行中
                    }

                    job.setPublishAVUser(AVUser.getCurrentUser());
                    job.saveJobObject().saveInBackground(new SaveCallback() {
                        @Override
                        public void done(AVException e) {
                            loadingDialog.dismiss();
                            if (e == null) {
                                jianzhijiaApplacation.updateJobListFresh();
                                if (ifModify && !jianzhijiaApplacation.getCompanyUser().isIdentified()) {
                                    Dialog.Builder builder = null;
                                    builder = new SimpleDialog.Builder(R.style.SimpleDialogLight) {
                                        @Override
                                        public void onPositiveActionClicked(DialogFragment fragment) {
                                            ToastUtils.showToast(getApplicationContext(), "修改成功");
                                            PublishActivity.this.finish();
                                            super.onPositiveActionClicked(fragment);
                                        }

                                        @Override
                                        public void onNegativeActionClicked(DialogFragment fragment) {
                                            fragment.dismiss();
                                            startActivity(new Intent(getApplicationContext(), IdentificationActivity.class));
                                            finish();
                                            super.onNegativeActionClicked(fragment);
                                        }
                                    };

                                    ((SimpleDialog.Builder) builder).message("您当前的账号尚未认证，修改信息之后管理员将会在1-2小时内对您的文章进行审核")
                                                .positiveAction("我知道了")
                                                .negativeAction("现在认证").title("提示");
                                    DialogFragment fragment = DialogFragment.newInstance(builder);
                                    fragment.show(getSupportFragmentManager(), null);
                                } else if (ifModify && jianzhijiaApplacation.getCompanyUser().isIdentified()) {
                                    ToastUtils.showToast(getApplicationContext(), "修改成功");
                                    PublishActivity.this.finish();
                                } else if (!ifModify && jianzhijiaApplacation.getCompanyUser().isIdentified()) {
                                    ToastUtils.showToast(getApplicationContext(), "发布成功");
                                    PublishActivity.this.finish();
                                } else if (!ifModify && !jianzhijiaApplacation.getCompanyUser().isIdentified()) {
                                    Dialog.Builder builder = null;
                                    builder = new SimpleDialog.Builder(R.style.SimpleDialogLight) {
                                        @Override
                                        public void onPositiveActionClicked(DialogFragment fragment) {
                                            ToastUtils.showToast(getApplicationContext(), "发布成功");
                                            PublishActivity.this.finish();
                                            super.onPositiveActionClicked(fragment);
                                        }

                                        @Override
                                        public void onNegativeActionClicked(DialogFragment fragment) {
                                            fragment.dismiss();
                                            startActivity(new Intent(getApplicationContext(), IdentificationActivity.class));
                                            finish();
                                            super.onNegativeActionClicked(fragment);
                                        }
                                    };

                                    ((SimpleDialog.Builder) builder).message("您当前的账号尚未认证，发布文章信息之后管理员将会在1-2小时内对您的文章进行审核")
                                                .positiveAction("我知道了")
                                                .negativeAction("现在认证").title("提示");
                                    DialogFragment fragment = DialogFragment.newInstance(builder);
                                    fragment.show(getSupportFragmentManager(), null);
                                }

                            } else {

                                ToastUtils.showToast(getApplicationContext(), ExceptionUtils.getExceptionInfo(e));
                            }
                        }
                    });
                }
            }
        });
    }

    private void getDataFromEdt() {
        jobName = edtJobName.getText().toString().trim();
        workDate = edtJobDate.getText().toString().trim();
        workTime = edtJobTime.getText().toString().trim();
        requestNum = edtPeopleNum.getText().toString().trim();
        salary = edtJobSalary.getText().toString().trim();
        describe = edtJobDescribe.getText().toString().trim();
        contactEmail = edtContactEmail.getText().toString().trim();
        contactPhone = edtContactPhone.getText().toString().trim();
        contactName = edtContactPeople.getText().toString().trim();
        workAddress = edtJobAddress.getText().toString().trim();
        hasReadProtocol = cbReadProtocol.isChecked();
    }

    @Override
    public void setJobType(int type, String name) {
        this.jobType = type;
        tvJobType.setText(name);
    }

    @Override
    public void setGenderType(int position, String name) {
        this.genderRequest = position + 1;
        tvGenderType.setText(name);
    }

    @Override
    public void setPayType(int position, String name) {
        this.payType = position + 1;
        tvPayType.setText(name);
    }

    @Override
    public void setCity(int position, String itemName) {
        this.cityId = position;
        tvChooseCity.setText(itemName);
    }

    @Override
    public void setProvince(int position, String itemName) {
        this.provinceId = position;
        this.tvChooseProvince.setText(itemName);
    }

    @Override
    public void setRegion(int position, String itemName) {
        this.regionId = position;
        this.tvChooseRegion.setText(itemName);
    }

    public void initModifyData() {
        edtJobName.setText(job.getJobName() + "");
        jobType = job.getJobType();
        tvJobType.setText(Data.JobTypeData[jobType]);
        payType = job.getPayType();
        tvPayType.setText(Data.payTypeData[payType - 1]);
        genderRequest = job.getGenderRequest();
        tvGenderType.setText(Data.genderTypeData[genderRequest - 1]);
        edtJobDate.setText(job.getWorkDate() + "");
        edtJobTime.setText(job.getWorkTime() + "");
        edtJobSalary.setText(job.getSalary() + "");
        edtJobDescribe.setText(job.getDescribe() + "");
        edtContactPhone.setText(job.getContactPhone() + "");
        edtContactEmail.setText(job.getContactEmail() + "");
        edtJobAddress.setText(job.getWorkAddress() + "");
        edtPeopleNum.setText(job.getRequestNum() + "");
        edtContactPeople.setText(job.getContactName() + "");
        provinceId = job.getProvinceId();
        cityId = job.getCityId();
        regionId = job.getRegionId();
        tvChooseProvince.setText(Data.provinceData[provinceId]);
        tvChooseCity.setText(Data.cityData[cityId]);
        tvChooseRegion.setText(Data.regionData[regionId]);
    }


    @Override
    public void afterGetProvinces(ArrayList<Province> provinces) {
        netWorIsOn = false;
        if (provinces == null) {
            ToastUtils.showToast(getApplicationContext(), "网络错误，无法获取国别列表");
            return;
        } else if (provinces.size() == 0) {
            ToastUtils.showToast(getApplicationContext(), "国别列表为空");
            return;
        }

        publishPopupWindowProvince = PublishPopupWindowProvince.newInstance(this, this, llParent, provinces);
        publishPopupWindowProvince.showAtLocation(llParent, Gravity.CENTER, 0, 0);
    }

    @Override
    public void afterGetCities(ArrayList<City> cities) {
        netWorIsOn = false;
        if (cities == null) {
            ToastUtils.showToast(getApplicationContext(), "网络错误，无法获取地区列表");
            return;
        } else if (cities.size() == 0) {
            ToastUtils.showToast(getApplicationContext(), "地区列表为空");
            return;
        }

        publishPopupWindowCity = PublishPopupWindowCity.newInstance(this, this, llParent, cities);
        publishPopupWindowCity.showAtLocation(llParent, Gravity.CENTER, 0, 0);
    }

    @Override
    public void afterGetRegions(ArrayList<Region> regions) {

        netWorIsOn = false;
        if (regions == null) {
            ToastUtils.showToast(getApplicationContext(), "网络错误，无法获取城市列表");
            return;
        } else if (regions.size() == 0) {
            ToastUtils.showToast(getApplicationContext(), "城市列表为空");
            return;
        }
        publishPopupWindowRegion = PublishPopupWindowRegion.newInstance(this, this, llParent, regions);
        publishPopupWindowRegion.showAtLocation(llParent, Gravity.CENTER, 0, 0);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SELECT_CONTACTOR_CODE && resultCode == RESULT_OK && data != null) {
            Uri resultUri = data.getData();
            Cursor cursor = getContentResolver().query(resultUri, null, null, null, null);
            cursor.moveToFirst();
            String transCustomorName = null;
            String transCustomorPhone = null;
            try {
                transCustomorPhone = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));
                transCustomorName = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
                ToastUtils.showToast(getApplicationContext(), "读取联系人失败，请手动输入");
                return;
            }
            if (transCustomorPhone != null) {
                edtContactPhone.setText(transCustomorPhone);
            }
            if (transCustomorName != null) {
                edtContactPeople.setText(transCustomorName);
            }
            return;
        }
    }



    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            String s = "您确认要离开发布界面吗";
            showMaterialDialog(s, "提示", new DialogAction() {
                @Override
                public void positiveAction() {
                    finish();
                }

                @Override
                public void negativeAction() {

                }
            });

        }
        return false;
    }


    private interface DialogAction {
        void positiveAction();
        void negativeAction();
    }


    private void showMaterialDialog(String content, String title, final DialogAction dialogAction) {

        Dialog.Builder builder = null;
        builder = new SimpleDialog.Builder(R.style.SimpleDialogLight) {
            @Override
            public void onPositiveActionClicked(DialogFragment fragment) {
                fragment.dismiss();
                dialogAction.positiveAction();
                super.onPositiveActionClicked(fragment);
            }

            @Override
            public void onNegativeActionClicked(DialogFragment fragment) {
                fragment.dismiss();
                dialogAction.negativeAction();
                super.onNegativeActionClicked(fragment);
            }
        };

        ((SimpleDialog.Builder) builder).message(content)
                    .positiveAction("确认")
                    .negativeAction("取消").title(title);
        DialogFragment fragment = DialogFragment.newInstance(builder);
        fragment.setCancelable(false);
        fragment.show(getSupportFragmentManager(), null);
    }
}
